package com.furnitur.modules.admin.controller.system;

import com.furnitur.common.api.CommonResult;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Collections;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/file")
public class FileController {

    private static final Logger log = LoggerFactory.getLogger(FileController.class);

    @Value("${minio.endpoint}")
    private String endpoint;

    @Value("${minio.bucket-name}")
    private String bucketName;

    @Autowired
    private MinioClient minioClient;

    @PostMapping("/upload/image")
    public CommonResult<Map<String, String>> uploadImage(@RequestParam("file") MultipartFile file) {
        try {
            String fileName = "merchant/" + UUID.randomUUID().toString() + 
                            file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            
            minioClient.putObject(
                PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(fileName)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(file.getContentType())
                    .build()
            );
            
            // 返回完整的 MinIO URL，确保不以 / 结尾
            String baseUrl = endpoint.endsWith("/") ? endpoint.substring(0, endpoint.length() - 1) : endpoint;
            String url = String.format("%s/%s/%s", baseUrl, bucketName, fileName);
            log.info("Uploaded file URL: {}", url);
            
            return CommonResult.success(Collections.singletonMap("url", url));
        } catch (Exception e) {
            log.error("File upload error", e);
            return CommonResult.failed("文件上传失败: " + e.getMessage());
        }
    }
} 